<?php
namespace Blog\Controller;
use Think\Controller;

class IndexController extends Controller
{

    function index(){
        echo "hello";
    }    

    function register2(){
        $this->display();
    }

    function register(){
          //提交表单
          if (IS_AJAX) {
            $userModel = D('Home/User'); //M('user')
            $username=I('post.username');
            $password=md5(I('post.password'));

            $user=array();
            $user['username']=$username;
            $user['password']=$password;

            if ($userModel->where(array('username'=>$username))->count()>0){
                $this->ajaxReturn(
                    array(
                        code=>-1,
                        data=> null,
                        message=>'用户已经注册',
                    )
                );
                return;
            }

            $uid=$userModel->add($user);             
            if ($uid) {
                //验证通过
                $this->ajaxReturn(
                    array(
                        code=>0,
                        data=>$uid, //输出用户信息
                        message=>'用户用户身份验证通过。',
                    )
                );
            } else {
                   $this->ajaxReturn(
                    array(
                        code=>-1,
                        data=> null,
                        message=>'注册失败。',
                    )
                );
            }
        } else {           
            $this->display();
        }
    }

    function login()
    {
           //提交表单
           if (IS_AJAX) {
            $userModel = D('Home/User'); //M('user')
            // $userModel=new \Home\Model\User();
            $username=I('post.username');
            //$username= $_POST['username'];
            $password=md5(I('post.password'));
           // $remember=I('post.remember', false, 'intval');

            $user=$userModel->login($username, $password, false);
            //判断指定的用户名的记录是否已经存在
            if ($user) {
                //验证通过
                $this->ajaxReturn(
                    array(
                        code=>0,
                        data=>$user, //输出用户信息
                        message=>'用户用户身份验证通过。',
                    )
                );
            } else {
                   $this->ajaxReturn(
                    array(
                        code=>-1,
                        data=> null,
                        message=>'身份验证失败。',
                    )
                );
            }
        } else {
            if (is_login()) {
                redirect(U('Home/Index/index'));
            }
            //显示登陆页面
            $this->display();
        }
       
    }


}